package com.example.papercut.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.nio.file.FileSystems; // 确保导入

@RestController
@RequestMapping("/api/files")
public class FileController {

    // ✅ 配置文件保存的相对目录名
    private static final String UPLOAD_DIR_NAME = "uploads/creations/"; 
    // ✅ 配置文件访问的baseURL (本地开发通常是服务器地址)
    private static final String BASE_URL = "http://localhost:8080/"; 

    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("{\"message\": \"上传文件不能为空\"}");
        }

        try {
            // 1. 获取 CWD 的绝对路径
            String currentWorkingDir = FileSystems.getDefault().getPath("").toAbsolutePath().toString();
            
            // 2. 拼接完整的绝对上传路径
            Path uploadPath = Paths.get(currentWorkingDir, UPLOAD_DIR_NAME);
            
            // 3. 确保上传目录存在 (现在使用绝对路径创建)
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // ... (省略生成唯一文件名和扩展名的逻辑) ...
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            int dotIndex = originalFilename.lastIndexOf('.');
            if (dotIndex > 0) {
                extension = originalFilename.substring(dotIndex);
            }
            String uniqueFileName = System.currentTimeMillis() + extension;

            // 4. 将文件写入磁盘 (使用绝对路径)
            Path filePath = uploadPath.resolve(uniqueFileName);
            file.transferTo(filePath.toFile());

            // 5. 构建完整的访问 URL
            String fileUrl = BASE_URL + UPLOAD_DIR_NAME + uniqueFileName; 

            // 6. 返回包含 URL 的 JSON 结构
            Map<String, String> response = new HashMap<>();
            response.put("url", fileUrl);
            return ResponseEntity.ok(response);

        } catch (IOException e) {
            e.printStackTrace(); // 再次打印异常堆栈
            return ResponseEntity.internalServerError().body("{\"message\": \"文件上传失败: " + e.getMessage() + "\"}");
        }
    }
}